package summer.hot100;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution39 {
    List<List<Integer>> res = new ArrayList<>();

    LinkedList<Integer> tmp = new LinkedList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtrack(candidates, target, 0);
        return res;
    }

    public void backtrack(int[] candidates, int target, int index) {
        if (target == 0) {
            res.add(new ArrayList<>(tmp));
            return;
        }
        if (target < 0) return;
        for (int i = index; i < candidates.length; i++) {
            target -= candidates[i];
            tmp.add(candidates[i]);
            backtrack(candidates, target, i);
            target += candidates[i];
            tmp.removeLast();
        }
    }
}
